
//  ReminderDetailView.m
//  Reminders
//
//  Created by Nearsoft User on 8/2/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#define REPEAT_PICKER  0
#define DAY_PICKER     1
#define TIME_PICKER    2
#define NO_PICKER      4

const int kPickerSize           = 216;
const int kNavigationbarSize    = 44;
const int kToolbarSize          = 44;
const int kViewWidth            = 320;
const int kViewHeight           = 416;
const int kDateScroll           = 210;
const int kRepearScroll         = 305;
const bool kTest                = NO;

#import "ReminderDetailView.h"

@interface ReminderDetailView ()

@end

@implementation ReminderDetailView

@synthesize reminder;
@synthesize reminderTitle;
@synthesize reminderNotes;
@synthesize edit;

#pragma mark - Custom Methods
/**
 * Method name: onSave
 * Description: saves the reminder if it's new or edits it if already exist
 * Parameters: 
 */
- (void)onSave
{
    // If the title text field is empty an alert is displayed
    if ([reminderTitle.text isEqualToString:@""])
    {
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Title Missing" message:@"Title field must contain text."
                              delegate:nil
                              cancelButtonTitle:@"Close"
                              otherButtonTitles:nil];
        [alert show];

        return;
    }

    if ([dateString dateIsOlderThanToday:[dateString parseDates:[dateString stringToDay:dayButton.titleLabel.text] time:[dateString stringToTime:timeButton.titleLabel.text]]] && !kTest)
    {
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Don't live on the past" message:@"The selected date must be a future date."
                              delegate:nil
                              cancelButtonTitle:@"Close"
                              otherButtonTitles:nil];
        [alert show];
        
        return;
    }

    if (reminder == nil)
        reminder = [[Reminder alloc] init];

    // Set the reminder properties
    reminder.title = [reminderTitle text];
    reminder.date = [dateString parseDates:[dateString stringToDay:dayButton.currentTitle] time:[dateString stringToTime:timeButton.currentTitle]];
    reminder.notes = [reminderNotes text];
    reminder.repeat = [repeatList indexOfObject:[repeatButton.titleLabel text]];

    // Save the reminder into the databse and schedule its notification
    [reminder saveToDataBase];

    // Pops the view with animation
    [self.navigationController popViewControllerAnimated:YES];
}

/**
  * Method name: backgroundTap
  * Description: Dismiss any subview being shown when user taps the background
  * Parameters: 
  */
- (IBAction)backgroundTap
{
    [self dismissPickerView];
    [reminderNotes resignFirstResponder];
    [reminderTitle resignFirstResponder];
    elementShown = NO;
}

/**
 * Method name: animateToElement
 * Description: moves the view when a picker or keyboard is displayed
 * Parameters:  distance: the number of pixels the view will move
 */
- (void)animateToElement:(NSInteger)distance
{
    [UIScrollView beginAnimations: @"anim" context: nil];
    [UIScrollView setAnimationBeginsFromCurrentState: YES];
    [UIScrollView setAnimationDuration: 0.3f];

    // If there is a distance, set the view so it can be scrolled and scroll it
    if (distance)
    {
        [scroll setContentSize:CGSizeMake(kViewWidth, kViewHeight + kPickerSize)];
        scroll.scrollEnabled = TRUE;
        [scroll scrollRectToVisible:CGRectMake(0, distance, kViewWidth , distance + 1) animated:NO];
    }
    else    // else the view scrolls up and disables the scroll
    {
        [scroll scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
        scroll.scrollEnabled = FALSE;
    }

    // Starts the scroll animation
    [UIScrollView commitAnimations];
}

#pragma mark - Custom Pickers Methods
/**
 * Method name: okPicker
 * Description: called when a picker ok button is pressed and sets the title for the corresponding button
 * Parameters: 
 */
- (void)okPicker
{
    if (currentPicker == REPEAT_PICKER) // Ok from repeatPicker
    {
        // Reads the element of the repeat picker at the selceted position and sets the title of the repeat button as the selected element
        repeatRow = [repeatPicker selectedRowInComponent:0];
        [repeatButton setTitle:[repeatList objectAtIndex:repeatRow] forState:UIControlStateNormal];
    }
    else
    {
        NSDateFormatter* pickerFormatter = [[NSDateFormatter alloc] init];

        if (currentPicker == DAY_PICKER) // Ok from dayPicker
        {
            // Reads the elements of the day picker at the selected position, convert it to string and sets the title of the day button as that string
            [pickerFormatter setDateStyle:NSDateFormatterLongStyle];
            [pickerFormatter setTimeStyle:NSDateFormatterNoStyle];
            [dayButton setTitle:[pickerFormatter stringFromDate:[dayPicker date]] forState:UIControlStateNormal];
        }
        else if (currentPicker == TIME_PICKER) // Ok from timePicker
        {
            // Reads the elements of the time picker at the selected position, convert it to string and sets the title of the time button as that string
            [pickerFormatter setDateStyle:NSDateFormatterNoStyle];
            [pickerFormatter setTimeStyle:NSDateFormatterShortStyle];
            [timeButton setTitle:[pickerFormatter stringFromDate:[timePicker date]] forState:UIControlStateNormal];
        }
    }

    // Dismiss the current picker view
    [self dismissPickerView];
}

/**
 * Method name: removeVies
 * Description: removes the toolbar and picker subviews
 * Parameters: 
 */
- (void)removeViews
{
    // Removes the picker from the view
    [[self.view viewWithTag:10] removeFromSuperview];

    // Removes the toolbar from the view
    [[self.view viewWithTag:11] removeFromSuperview];
}

/**
 * Method name: dismissPickerView
 * Description: sets the disappearing animation for the toolbar and picker subviews
 * Parameters: 
 */
- (void)dismissPickerView
{
    // Scrolls the view back
    [self animateToElement:0];

    // Sets the dismiss movement
    [UIView beginAnimations:@"MoveOut" context:nil];
    [self.view viewWithTag:10].frame = CGRectMake(0, self.view.bounds.size.height, kViewWidth, kPickerSize);
    [self.view viewWithTag:11].frame = CGRectMake(0, self.view.bounds.size.height, kViewWidth, kToolbarSize);
    [UIView setAnimationDelegate:self];

    // Removes the views when movement stops
    [UIView setAnimationDidStopSelector:@selector(removeViews)];

    // Starts the animation
    [UIView commitAnimations];

    // Element is being shown is now no and no picker is currently active
    currentPicker = NO_PICKER;
    elementShown = NO;
}

/**
 * Method name: showRepeatPicker
 * Description: shows the repeat picker subview with its respective toolbar
 * Parameters:  sender: not in use at the moment
 */
-(IBAction)showRepeatPicker:(id)sender
{
    // If the repeat picker is not on the view
    if (currentPicker != REPEAT_PICKER || elementShown == NO)
    {
        // If there is an element already being shown dismiss it
        if (elementShown == YES)
            [self backgroundTap];

        // Moves the view so the button is not behind the picker
        [self animateToElement:kRepearScroll];

        // If repeat picker doesn't exists creat it
        if (repeatPicker == nil)
        {
            repeatPicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height + kToolbarSize, kViewWidth, kPickerSize)];
            repeatPicker.showsSelectionIndicator = YES;
            repeatPicker.dataSource = (id)self;
            repeatPicker.delegate = (id)self;
        }

        // Set the initial element in the picker as the element at position "repeatRow"
        [repeatPicker selectRow:repeatRow inComponent:0 animated:NO];

        // Create and sets the toolbar with a Done button
        UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height, kViewWidth, kToolbarSize)];
        toolBar.tag = 11;
        toolBar.barStyle = UIBarStyleBlackTranslucent;
        [toolBar setItems:[NSArray arrayWithObjects:
                           [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                           [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(okPicker)],
                           nil]];

        // Add the picker and toolbar as subviews
        [self.view addSubview:repeatPicker];
        [self.view addSubview:toolBar];

        // Sets the animation
        [UIView beginAnimations:@"MoveIn" context:nil];
        toolBar.frame = CGRectMake(0, self.view.bounds.size.height - kPickerSize - kToolbarSize, kViewWidth, kToolbarSize);
        repeatPicker.frame = CGRectMake(0, self.view.bounds.size.height - kPickerSize, kViewWidth, kPickerSize);
        repeatPicker.tag = 10;

        // Element is being shown is now yes and the current active picker is the repeat picker
        elementShown = YES;
        currentPicker = REPEAT_PICKER;
    }
}

/**
 * Method name: showTimePicker
 * Description: shows the time picker subview with its respective toolbar
 * Parameters:  sender: not in use at the moment
 */
-(IBAction)showTimePicker:(id)sender
{
    // If the time picker is not on the view
    if (currentPicker != TIME_PICKER || elementShown == NO)
    {
        // If there is an element already being shown dismiss it
        if (elementShown == YES)
            [self backgroundTap];

        // Moves the view so the button is not behind the picker
        [self animateToElement:kDateScroll];

        // If time picker doesn't exists creat it
        if (timePicker == nil)
        {
            timePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height + kToolbarSize, kViewWidth, kPickerSize)];
            timePicker.datePickerMode = UIDatePickerModeTime;
        }

        // If the date in the dayPicker is older than the current day
        if([dateString dateIsOlderThanToday:[dateString stringToDay:[[dayButton titleLabel] text]]] == YES)
        {
            // Set the current time as the minimum time
            if (!kTest)
                [timePicker setMinimumDate:[NSDate date]];
        }
        else
        {
            // Else reads the time from its button label and sets the initial time as that label text
            [timePicker setMinimumDate:nil];
        }

        [timePicker setDate:[dateString stringToTime:[[timeButton titleLabel]text]]];

        // Create and sets the toolbar with a Done button
        UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height, kViewWidth, kToolbarSize)];
        toolBar.tag = 11;
        toolBar.barStyle = UIBarStyleBlackTranslucent;
        [toolBar setItems:[NSArray arrayWithObjects:
                           [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                           [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(okPicker)],
                           nil]];

        // Add the picker and toolbar as subviews
        [self.view addSubview:timePicker];
        [self.view addSubview:toolBar];

        // Sets the animation
        [UIView beginAnimations:@"MoveIn" context:nil];
        toolBar.frame = CGRectMake(0, self.view.bounds.size.height-kPickerSize-kToolbarSize, kViewWidth, kToolbarSize);
        timePicker.frame = CGRectMake(0, self.view.bounds.size.height-kPickerSize, kViewWidth, kPickerSize);
        timePicker.tag = 10;

        // Element is being shown is now yes and the current active picker is the time picker
        elementShown = YES;
        currentPicker = TIME_PICKER;
    }
}

/**
 * Method name: showDatePicker
 * Description: shows the repeat picker subview with its respective toolbar
 * Parameters:  sender: not in use at the moment
 */
-(IBAction)showDatePicker:(id)sender
{
    // If the time picker is not on the view
    if (currentPicker != DAY_PICKER || elementShown == NO)
    {
        // If there is an element already being shown dismiss it
        if (elementShown == YES)
            [self backgroundTap];

        // Moves the view so the button is not behind the picker
        [self animateToElement:kDateScroll];

        // If time picker doesn't exists creat it
        if (dayPicker == nil)
        {
            dayPicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height+kToolbarSize, kViewWidth, kPickerSize)];

            if (!kTest)
                [dayPicker setMinimumDate:[NSDate date]];

            dayPicker.datePickerMode = UIDatePickerModeDate;
        }
        
        // Reads the date from its button label and sets the initial date as that label text
        [dayPicker setDate:[dateString stringToDay:[[dayButton titleLabel]text]]];

        // Create and sets the toolbar with a Done button
        UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height, kViewWidth, kToolbarSize)];
        toolBar.tag = 11;
        toolBar.barStyle = UIBarStyleBlackTranslucent;
        [toolBar setItems:[NSArray arrayWithObjects:
                           [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                           [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(okPicker)],
                           nil]];

        // Add the picker and toolbar as subviews
        [self.view addSubview:dayPicker];
        [self.view addSubview:toolBar];

        // Sets the animation
        [UIView beginAnimations:@"MoveIn" context:nil];
        toolBar.frame = CGRectMake(0, self.view.bounds.size.height-kPickerSize-kToolbarSize, kViewWidth, kToolbarSize);
        dayPicker.frame = CGRectMake(0, self.view.bounds.size.height-kPickerSize, kViewWidth, kPickerSize);
        dayPicker.tag = 10;

        // Element is being shown is now yes and the current active picker is the date picker
        elementShown = YES;
        currentPicker = DAY_PICKER;
    }
}

#pragma mark - Text Methods
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    if (elementShown == YES)
        [self backgroundTap];

    [self animateToElement:kDateScroll];
    elementShown = YES;

    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (elementShown == YES)
        [self backgroundTap];

    elementShown = YES;

    return YES;
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    [self animateToElement:0];
}


- (BOOL)textViewShouldReturn:(UITextField *)textView
{
    [textView resignFirstResponder];
    elementShown = NO;
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    elementShown = NO;

    return YES;
}

#pragma mark - Default Picker Methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
{
    return [repeatList count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;
{
    return [repeatList objectAtIndex:row];
}

#pragma mark - Default Methods
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
    }

    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Set the "Save" button on the navigation bar
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(onSave)];

    self.navigationItem.rightBarButtonItem.tintColor = self.navigationController.navigationBar.tintColor;

    // The repeat options for the reminders 
    repeatList = [[NSArray alloc] initWithObjects:@"Once", @"Every Day", @"Every Week", @"Every Month", nil];
    dateString = [[DateStrings alloc] init];

    scroll.isAccessibilityElement = YES;

    reminderTitle.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 0)];
    reminderTitle.leftViewMode = UITextFieldViewModeAlways;
}

- (void)viewDidUnload
{
    [super viewDidUnload];

    repeatList = nil;
    repeatPicker = nil;
    timePicker = nil;
    dayPicker = nil;
    scroll = nil;
    dateString = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    // No picker is currently active
    currentPicker = NO_PICKER;

    // There are not subview elements being show in the view
    elementShown = NO;

    // Sets scroll as the scroll view from within the subviews
    scroll = [self.view.subviews objectAtIndex:0];

    // If edit is no, this is a new reminder
    if (edit == NO)
    {
        self.title = @"New Reminder";

        // Sets the label text from the date button to the current date
        [dayButton setTitle:[dateString stringFromDay:[NSDate date]] forState:UIControlStateNormal];
        
        // Sets the label text from the time button to the current time
        [timeButton setTitle:[dateString stringFromTime:[NSDate date]] forState:UIControlStateNormal];
        
        // Sets the label text from the repeat button to the default initial element from repeatList
        [repeatButton setTitle:[repeatList objectAtIndex:0] forState:UIControlStateNormal];

        // The default selected row from the repeat list is 0
        repeatRow = 0;
    }
    else // The reminder already exists
    {
        self.title = @"Reminder Details";

        // Fill the text fields and button labels text with the reminder data
        [reminderTitle setText:[reminder title]];
        [dayButton setTitle:[dateString stringFromDay:[reminder date]] forState:UIControlStateNormal];
        [timeButton setTitle:[dateString stringFromTime:[reminder date]] forState:UIControlStateNormal];
        [reminderNotes setText:[reminder notes]];
        repeatRow = reminder.repeat;
        [repeatButton setTitle:[repeatList objectAtIndex:reminder.repeat] forState:UIControlStateNormal];
        [repeatPicker selectRow:repeatRow inComponent:0 animated:NO];
    }

    self.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"detailViewBackground.png"]];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
